﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Api.Core.Auth;
using Api.Core.Common.Auth;
using Api.Core.Common.Cache;
using Api.Core.Common.Extension;
using Api.Core.Common.Helper;
using Api.Core.IServices.User;
using Api.Core.Model;
using Api.Core.Model.Entity;
using Api.Core.Model.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

namespace Api.Core.Controllers
{
    public class LoginController : BaseController
    {
        private readonly IAuthServer _authServer;
        private readonly IUserService _userInfo;
        private readonly IRedisCache _cache;
        private readonly AuthSetting _authSetting;

        public LoginController(IAuthServer authServer
            , IUserService userInfo,
            IRedisCache cache,
            IOptions<AuthSetting> authSetting)
        {
            _authServer = authServer;
            _userInfo = userInfo;
            _cache = cache;
            _authSetting = authSetting.Value;

        }


        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public virtual async Task<BaseResponse<bool>> LoginAsync(UserViewModel model)
        {

            if (model.UserName.IsNullOrWhiteSpace() || model.PassWord.IsNullOrWhiteSpace())
            {
                return Result(false,Model.StatusCode.ParamsNull,"用户名和密码必传");
            }
            model.PassWord = model.PassWord.ToUpper();
            var userInfo = await _userInfo.QueryOne(x => x.UserName == model.UserName && x.PassWord == model.PassWord);
            if (userInfo == null  || userInfo.UserId.IsNullOrWhiteSpace())
            {
                return Result(false,Model.StatusCode.Fail,"用户不存在或密码错误");
            }

            var cacheToken = _cache.GetValue(userInfo.UserId);
            if (!string.IsNullOrWhiteSpace(cacheToken))
            {
                Result(cacheToken.Replace("\"", "")); 
            }

            var response = await _authServer.CreateAuthentication(model);
            if (!response.success)
            {
                return Result(false,Model.StatusCode.ErrorToken, response.message);
            }
            _cache.Set(userInfo.UserId, response.token, _authSetting.TokenLifetime * 2);
            return Result(true, Model.StatusCode.Success, "生成Token成功");
        }
    }
}
